#include "form_tf.h"
#include "ui_form_tf.h"
#include "pub_var.h"
#include <QSettings>
#include <QMessageBox>
#include <QDebug>
#include <QSqlError>
#include <QSqlRecord>
#include <QDateTime>
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>

Form_tf::Form_tf(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form_tf)
{

    ui->setupUi(this);
    //窗口标题
    this->setWindowTitle("退费管理－当前用户－"+pub::usr_name);

    QSettings setIni("clin.ini", QSettings::IniFormat);
    //恢复当前窗口位置
    QRect rct = setIni.value("windowState/tf").toRect();
    this->setGeometry(rct);

    //数据库连接
    qrm = new QSqlQuery(pub::db_m);
    qro = new QSqlQuery(pub::db_o);
    //qro2 = new QSqlQuery(pub::db_o);

    //预置退费类别
    ui->rbG->setChecked(true);

    //预置执行按钮无效
    ui->pbExecute->setEnabled(false);

    //列表字体
    ui->tvItemList->setFont(this->font());

//    if(pub::usr_code  != "000064" && pub::usr_code  != "010025"){
//        ui->rbS->setChecked(true);
//        ui->rbG->setEnabled(false);
//    }else{
//        ui->rbG->setChecked(true);
//        ui->rbG->setEnabled(true);
//    }
    //网络参数

    //request.setUrl(QUrl(pub::hos_ybjy));
    //request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

}

Form_tf::~Form_tf()
{
    delete ui;
}
void Form_tf::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    QSettings setIni("clin.ini", QSettings::IniFormat);
    setIni.setValue("windowState/tf", QVariant(this->geometry()));

}

void Form_tf::resizeEvent(QResizeEvent *event)
{

    Q_UNUSED(event);
    //窗口界面大小变化，重新设定

//    ui->tvBzh->setColumnWidth(0, (ui->tvBzh->width() -50 ) * 0.33);
//    ui->tvBzh->setColumnWidth(1, (ui->tvBzh->width() -50 ) * 0.33);
//    ui->tvBzh->setColumnWidth(2, (ui->tvBzh->width() -50 ) * 0.33);

//    ui->tvXmmx->setColumnWidth(0, (ui->tvXmmx->width() -50 ) * 0.35);
//    ui->tvXmmx->setColumnWidth(1, (ui->tvXmmx->width() -50 ) * 0.25);
//    ui->tvXmmx->setColumnWidth(2, (ui->tvXmmx->width() -50 ) * 0.1);
//    ui->tvXmmx->setColumnWidth(3, (ui->tvXmmx->width() -50 ) * 0.1);
//    ui->tvXmmx->setColumnWidth(4, (ui->tvXmmx->width() -50 ) * 0.2);

}

void Form_tf::on_pbSearch_clicked()
{
    //ui->pbSearch->setEnabled(false);
    //qApp->processEvents();  //刷新显示
    if(ui->rbG->isChecked()){   //挂号票

        sq = "select card_no,name,dept_name,to_char(reg_date,'yyyy-mm-dd hh24:mi:ss'),pact_name,"
             "oper_code,pact_code,invoice_no, valid_flag, ynsee, clinic_code, rowid, idenno, card_type "
             "from fin_opr_register where invoice_no = '" +
                pub::add0(ui->leFph->text(),12) + "'";

        mdList.setQuery(sq, pub::db_o);

        if(mdList.record(0).value("name").toString().isEmpty()){
            QMessageBox::information(this,"注意","未找到指定票据号的挂号费！");
            return;
        }

        mdList.setHeaderData(0, Qt::Horizontal, "门诊号");
        mdList.setHeaderData(1, Qt::Horizontal, "姓名");
        mdList.setHeaderData(2, Qt::Horizontal, "诊室");
        mdList.setHeaderData(3, Qt::Horizontal, "挂号时间");
        mdList.setHeaderData(4, Qt::Horizontal, "费别");
        mdList.setHeaderData(5, Qt::Horizontal, "操作员");
        double width = ui->tvItemList->width() - 50;
        ui->tvItemList->setModel(&mdList);
        ui->tvItemList->setColumnWidth(0, width * 0.15);
        ui->tvItemList->setColumnWidth(1, width * 0.15);
        ui->tvItemList->setColumnWidth(2, width * 0.2);
        ui->tvItemList->setColumnWidth(3, width * 0.25);
        ui->tvItemList->setColumnWidth(4, width * 0.125);
        ui->tvItemList->setColumnWidth(5, width * 0.125);
        ui->tvItemList->setColumnWidth(6, 0);
        ui->tvItemList->setColumnWidth(7, 0);
        ui->tvItemList->setColumnWidth(8, 0);
        ui->tvItemList->setColumnWidth(9, 0);
        ui->tvItemList->setColumnWidth(10, 0);
        ui->tvItemList->setColumnWidth(11, 0);
        ui->tvItemList->setColumnWidth(12, 0);
        ui->tvItemList->setColumnWidth(13, 0);

        mpPerson.clear();
        mpPerson["name"] = mdList.record(0).value("name").toString();
        mpPerson["idenno"] = mdList.record(0).value("idenno").toString();   //身份证号
        mpPerson["card_type"] = mdList.record(0).value("card_type").toString();     //病志号
        mpPerson["rowid"] = mdList.record(0).value("rowid").toString();      //rowid
        mpPerson["clinic_code"] = mdList.record(0).value("clinic_code").toString();   //clinic_code
        mpPerson["pact_code"] = mdList.record(0).value("pact_code").toString();       //pack_code

        if(mdList.record(0).value("valid_flag").toString() == "0"){
            QMessageBox::information(this,"注意","此号已经有过作废操作！");
            ui->pbExecute->setEnabled(false);
            return;
        }

        if(mdList.record(0).value("ynsee").toString() == "1"){
            QMessageBox::information(this,"注意","此号已经有过看诊记录，不能作废！");
            ui->pbExecute->setEnabled(false);
            return;
        }

        mpPerson["invoice_no"] = pub::add0(ui->leFph->text(),12);

        if(mpPerson["pact_code"] == "2"){   //医保挂号

//            if(pub::ybywzq.isEmpty()){
//                QMessageBox::information(this,"错误","没有进行医保登录，无法对医保号退费！");
//                ui->pbExecute->setEnabled(false);
//                return;
//            }

//            qrm->prepare("select lpbz, jyfs from com_business where "
//                         "clinic_code = '" + mpPerson["clinic_code"] + "' and jyfs is not null");

//            qrm->exec();
//            if(qrm->next()){
//                mpPerson["token"] = qrm->value(0).toString();//令牌 VARHCAR2(40)用于业务处理验证
//                mpPerson["insurance_mode"] = qrm->value(1).toString(); //医保状态，card , code , id
//            }else{
//                QMessageBox::information(this,"错误","com_business 检索失败，无法进行作废操作！");
//                return;
//            }

            sq = "select setl_id, mdtrt_id, psn_no, insuplc_admdvs from fin_ipr_siinmaininfo "
                 " where inpatient_no = '" + mpPerson["clinic_code"] + "' "
                 " and invoice_no = '" + pub::add0(ui->leFph->text(),12) +"'";
qDebug()<<sq;
            qro->exec(sq);
            if(qro->next()){
                //mpPerson["token"] = qrm->value(0).toString();//令牌 VARHCAR2(40)用于业务处理验证
                //mpPerson["insurance_mode"] = qrm->value(1).toString(); //医保状态，card , code , id
                mpPerson["setl_id"] = qro->value(0).toString();
                mpPerson["mdtrt_id"] = qro->value(1).toString();
                mpPerson["psn_no"] = qro->value(2).toString();
                mpPerson["insuplc_admdvs"] = qro->value(3).toString();
qDebug()<<mpPerson["setl_id"]<<mpPerson["mdtrt_id"]<<mpPerson["psn_no"]<<mpPerson["insuplc_admdvs"];

            }else{
                QMessageBox::information(this,"错误","fin_ipr_siinmaininfo 检索失败，无法进行作废操作！");

                return;
            }

        }

        ui->pbExecute->setEnabled(true);

    }else{      //门诊发票
        QString invo_no = pub::add0(ui->leFph->text(),12);
        //sq = "select item_name, specs, price_unit, quantity/qty quantityqty , sale_price,"
        //     " (quantity / qty) * sale_price je, recipe_no, "
        //     " inpatient_no, apply_no, charge_flag from met_nui_cancelitem "
        //     " where bill_no ='" + invo_no + "'";
        sq = "select item_name, specs, price_unit, qty/pack_qty , unit_price,"
             " (qty/pack_qty) * unit_price , recipe_no, "
             " clinic_code, cancel_flag,drug_flag from fin_opb_feedetail "
             " where invoice_no ='" + invo_no + "'";

        mdList.setQuery(sq, pub::db_o);

        if(mdList.record(0).value("item_name").toString().isEmpty()){
            QMessageBox::information(this,"注意","找不到指定的发票号，退票类别选择是否正确？");
            return;
        }

        mdList.setHeaderData(0, Qt::Horizontal, "品名");
        mdList.setHeaderData(1, Qt::Horizontal, "规格");
        mdList.setHeaderData(2, Qt::Horizontal, "单位");
        mdList.setHeaderData(3, Qt::Horizontal, "数量");
        mdList.setHeaderData(4, Qt::Horizontal, "价格");
        mdList.setHeaderData(5, Qt::Horizontal, "金额");
        double width = ui->tvItemList->width() - 50;
        ui->tvItemList->setModel(&mdList);
        ui->tvItemList->setColumnWidth(0, width * 0.3);
        ui->tvItemList->setColumnWidth(1, width * 0.2);
        ui->tvItemList->setColumnWidth(2, width * 0.1);
        ui->tvItemList->setColumnWidth(3, width * 0.1);
        ui->tvItemList->setColumnWidth(4, width * 0.15);
        ui->tvItemList->setColumnWidth(5, width * 0.15);
        ui->tvItemList->setColumnWidth(6, 0);
        ui->tvItemList->setColumnWidth(7, 0);
        ui->tvItemList->setColumnWidth(8, 0);
        ui->tvItemList->setColumnWidth(9, 0);

        mpPerson.clear();
        mpPerson["clinic_code"] = mdList.record(0).value("clinic_code").toString();   //
        mpPerson["invoice_no"] = invo_no;      //
        mpPerson["drug_flag"] = mdList.record(0).value("drug_flag").toString();   //

        if(mdList.record(0).value("cancel_flag").toString() == "0"){
            QMessageBox::information(this,"注意","此号已经有过作废操作！");
            ui->pbExecute->setEnabled(false);
            return;
        }

        if(mpPerson["drug_flag"] == "1"){
            qro->exec("select * from MET_NUI_CANCELITEM where bill_no = '" + invo_no + "'");
            //暂时只检查数据有无，不核查项目是否完全一致。
            if(!qro->next()){
                QMessageBox::information(this,"注意","药品收费项目必须先经过药局退费审核！");
                ui->pbExecute->setEnabled(false);
                return;
            }
        }

        qro->prepare("select pact_code from fin_opb_invoiceinfo where invoice_no = :ivno "
                     " and trans_type = '1' ");
        qro->bindValue(":ivno", invo_no);
        qro->exec();
        if(qro->next()){
            mpPerson["pact_code"] = qro->value(0).toString();
        }else{
            QMessageBox::information(this,"错误","fin_opb_invoiceinfo 检索失败，无法确定收费类别！");
            return;
        }

        if(mpPerson["pact_code"] == "2"){   //医保挂号
//            if(pub::ybywzq.isEmpty()){
//                QMessageBox::information(this,"错误","没有进行医保登录，无法对医保号退费！");
//                ui->pbExecute->setEnabled(false);
//                return;
//            }
            qrm->prepare("select lpbz, jyfs from com_business where "
                         "clinic_code = '" + mpPerson["clinic_code"] + "'  and jyfs is not null");
            qrm->exec();
            if(qrm->next()){
                mpPerson["token"] = qrm->value(0).toString();//令牌 VARHCAR2(40)用于业务处理验证
                mpPerson["insurance_mode"] = qrm->value(1).toString(); //医保状态，card , code , id
            }else{
                QMessageBox::information(this,"错误","com_business 检索失败，无法进行作废操作！");
                return;
            }

            qro->prepare("select name,idenno, card_type from fin_opr_register where clinic_code = :clcd");
            qro->bindValue(":clcd", mpPerson["clinic_code"]);
            qro->exec();
            if(qro->next()){
                mpPerson["name"] = qro->value(0).toString();
                mpPerson["idenno"] = qro->value(1).toString();
                mpPerson["card_type"] = qro->value(2).toString();
            }else{
                QMessageBox::information(this,"错误"," register 检索失败，无法进行作废操作！");
                return;
            }
        }
        ui->pbExecute->setEnabled(true);
    }

    //ui->pbSearch->setEnabled(true);
}

void Form_tf::on_pbExecute_clicked()
{
    ui->pbExecute->setEnabled(false);
    qApp->processEvents();  //刷新界面显示
    if(ui->rbG->isChecked()){
        if(ghtp()){
            QMessageBox::information(this,"注意","挂号退票操作成功！");
        }
    }else if(ui->rbS->isChecked()){
        if(fptp()){
            QMessageBox::information(this,"注意","发票退票操作成功！");
        }
    }
    ui->pbExecute->setEnabled(false);
}

bool Form_tf::ghtp()
{

    QJsonObject in;
    putBaseIn(  in, "2208") ;

    QJsonObject inpu,inpud;

    inpu.insert("setl_id", mpPerson["setl_id"]); //
    inpu.insert("mdtrt_id",mpPerson["mdtrt_id"]); //
    inpu.insert("psn_no", mpPerson["psn_no"]);      //

    inpud.insert("data",inpu);
    in.insert("input", inpud);

    QJsonDocument indoc ;
    indoc.setObject(in);

    QNetworkRequest request;
    QNetworkAccessManager* naManager = new QNetworkAccessManager();
    QMetaObject::Connection connRet =
            QObject::connect(naManager, SIGNAL(finished(QNetworkReply*)),
                             this, SLOT(postRequestFinished(QNetworkReply*)));
    Q_ASSERT(connRet);

    request.setUrl(QUrl(pub::hos_ybjy));
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    if(mpPerson["pact_code"] == "2"){ //医保挂号

        httpSuccess = false;
        httpFinished = false;
        //rpl =
                naManager->post(request, indoc.toJson());


        while(true){
            qDebug()<<"http 2208 ..."<<httpFinished;
            QThread::msleep(1330);

            qDebug()<<     " wait for httpFinished       "<<httpFinished;
            if(httpFinished){
                //disconnect(naManager, SIGNAL(finished(QNetworkReply*)),this, SLOT(postRequestFinished(QNetworkReply*)));
                qDebug()<<" request 2208 is returned";
                break;
            }
        }
    }

    if(httpFinished && httpSuccess){
        if(!saveSI()){    //保存退费交易

            QMessageBox::information(this,"错误","保存医保数据返回异常！");
            return false;
        }

    }else{
            QMessageBox::information(this,"错误","httpFinished && httpSuccess");
        return false;
    }





    //复制原挂号记录记录
    qro->prepare("insert into fin_opr_register "
         "(clinic_code,trans_type,card_no,reg_date,noon_code,name,idenno,sex_code,birthday,"
         "rela_phone,address,card_type,paykind_code,paykind_name,pact_code,pact_name,"
         "mcard_no,reglevl_code,reglevl_name,dept_code,dept_name,schema_no,order_no,seeno,"
         "begin_time,end_time,doct_code,doct_name,ynregchrg,invoice_no,recipe_no,ynbook,ynfr,"
         "append_flag,reg_fee,chck_fee,diag_fee,oth_fee,own_cost,pub_cost,pay_cost,"
         "valid_flag,oper_code,oper_date,cancel_opcd,cancel_date,medical_type,icd_code,exam_code,"
         "exam_date,check_flag,check_opcd,check_date,balance_flag,balance_no,balance_opcd,"
         "balance_date,ynsee,see_date,triage_flag,triage_opcd,triage_date,print_invoicecnt,"
         "see_dpcd,see_docd,in_source,is_sendinhoscase,is_encryptname,normalname,in_date,"
         "out_date,zg,in_state,eco_cost,is_account,is_emergency,mark1,receipt_doct_code,"
         "receipt_doct_date,receipt_flag,account_no,emr_regid) "
         "select "
         "clinic_code,'2',card_no,reg_date,noon_code,name,idenno,sex_code,birthday,"
         "rela_phone,address,card_type,paykind_code,paykind_name,pact_code,pact_name,"
         "mcard_no,reglevl_code,reglevl_name,dept_code,dept_name,schema_no,order_no,seeno,"
         "begin_time,end_time,doct_code,doct_name,ynregchrg,invoice_no,recipe_no,ynbook,ynfr,"
         "append_flag,0-reg_fee,0-chck_fee,0-diag_fee,0-oth_fee,0-own_cost,0-pub_cost,0-pay_cost,"
         "'0',:cancel_opcd,sysdate,:cancel_opcd,sysdate,medical_type,icd_code,exam_code,"
         "exam_date,check_flag,check_opcd,check_date,'0','','',"
         "balance_date,ynsee,see_date,triage_flag,triage_opcd,triage_date,print_invoicecnt,"
         "see_dpcd,see_docd,in_source,is_sendinhoscase,is_encryptname,normalname,in_date,"
         "out_date,zg,in_state,eco_cost,is_account,is_emergency,mark1,receipt_doct_code,"
         "receipt_doct_date,receipt_flag,account_no,emr_regid "
         "from fin_opr_register where rowid = :myRowid");
    qro->bindValue(":cancel_opcd", pub::usr_code);
    qro->bindValue(":myRowid", mpPerson["rowid"] );

    if(!qro->exec()){
        QMessageBox::information(this,"错误","无法保存 fin_opr_register 作废数据！"+qro->lastError().text());
        qDebug()<<qro->lastQuery();
        return false;
    }
    //变更原始记录，设置作废标志
    qro->prepare("update fin_opr_register set valid_flag = '0', cancel_opcd = :cancel_opcd,"
                 "cancel_date = sysdate where rowid = :myRowid");
    qro->bindValue(":cancel_opcd",pub::usr_code);
    qro->bindValue(":myRowid", mpPerson["rowid"]);

    if(!qro->exec()){
        QMessageBox::information(this,"错误","插入 update fin_opr_register 失败！"+qro->lastError().text());
        qDebug()<<qro->lastError().text();
        return false;
    }

    mdList.setQuery(NULL);

    return true;

}

bool Form_tf::saveSI()
{
qDebug()<<"saveSI";
    qro->exec("select max(to_number(BALANCE_NO)) from fin_ipr_siinmaininfo "
              " where inpatient_no = '" + mpPerson["clinic_code"] + "'");
    int blance_no;
    if(qro->next()){ //有记录，加 1
        blance_no = qro->value(0).toInt() + 1;
    }else{  //无记录， 赋初值 0
        blance_no = 0;
    }
qDebug()<<"saveSI"<<blance_no;
    qro->prepare("insert into fin_ipr_siinmaininfo ("
                 "insuplc_admdvs,psn_no,mdtrt_id,ipt_otp_no,msgid,setl_id,"
                 "trans_type,Inpatient_No,Balance_No,Invoice_No,Medical_Type,Patient_No,"
                 "Card_No,Mcard_No,App_No,Procreate_Pcno,Si_Begindate,Si_State,Name,"
                 "Sex_Code,Idenno,Spell_Code,Birthday,Empl_Type,Work_Name,Clinic_Diagnose,"
                 "Dept_Code,Dept_Name,Paykind_Code,Pact_Code,Pact_Name,Bed_No,In_Date,"
                 "In_Diagnosedate,In_Diagnose,In_Diagnosename,Oper_Code,Oper_Date,"
                 "Reg_No,Fee_Times,Hos_Cost,Year_Cost,Out_Date,Out_Diagnose,"
                 "Out_Diagnosename,Balance_Date,Tot_Cost,Pay_Cost,Pub_Cost,Item_Paycost,"
                 "Base_Cost,Item_Ylcost,Item_Paycost2,Own_Cost,Over_Cost,Valid_Flag,"
                 "Balance_State,Remark,Official_Cost,Type_Code,Person_Type,"
                 "Primarydiagnosecode,Operatecode1,Operatecode2,Operatecode3,"
                 "Primarydiagnosename,overtake_owncost,BUSINESSSEQUENCE,"
                 "SERIOUSILLNESS_IN_COST,SERIOUSILLNESS_COST,SERIOUSILLNESS_TOTAL,"
                 "individualbalance"
                 ") select "
                 "insuplc_admdvs,psn_no,mdtrt_id,ipt_otp_no,"
                 "'" + msgid2208 + "',"
                 "'" + ret2208setlinfo.value("setl_id").toString() + "',"
                 "'2',Inpatient_No,:Balance_No,Invoice_No,Medical_Type,Patient_No,"
                 "Card_No,Mcard_No,App_No,Procreate_Pcno,Si_Begindate,Si_State,Name,"
                 "Sex_Code,Idenno,Spell_Code,Birthday,Empl_Type,Work_Name,Clinic_Diagnose,"
                 "Dept_Code,Dept_Name,Paykind_Code,Pact_Code,Pact_Name,Bed_No,In_Date,"
                 "In_Diagnosedate,In_Diagnose,In_Diagnosename,:Oper_Code,sysdate,"
                 "Reg_No,Fee_Times,Hos_Cost,Year_Cost,Out_Date,Out_Diagnose,"
                 "Out_Diagnosename, sysdate, 0 - Tot_Cost, 0 - Pay_Cost, 0 - Pub_Cost,"
                 "Item_Paycost,"
                 "Base_Cost,Item_Ylcost,Item_Paycost2, 0 - Own_Cost,Over_Cost,Valid_Flag,"
                 "Balance_State,Remark,Official_Cost,Type_Code,Person_Type,"
                 "Primarydiagnosecode,Operatecode1,Operatecode2,Operatecode3,"
                 "Primarydiagnosename,overtake_owncost,BUSINESSSEQUENCE,"
                 "SERIOUSILLNESS_IN_COST,SERIOUSILLNESS_COST,SERIOUSILLNESS_TOTAL,"
                 "individualbalance + Pay_Cost"
                 " from fin_ipr_siinmaininfo where invoice_no = :Invoice_No and rownum = 1 ");
    qro->bindValue(":Balance_No", QString::number(blance_no));//结算序号
    qro->bindValue(":Invoice_No",mpPerson["invoice_no"]);//发票号
    qro->bindValue(":Oper_Code", pub::usr_code);//操作员
    if(!qro->exec()){
        QMessageBox::information(this,"错误","插入 fin_ipr_siinmaininfo 失败！"+qro->lastError().text());
        qDebug()<<qro->lastQuery();
        qDebug()<<QString::number(blance_no)<<mpPerson["invoice_no"]<<pub::usr_code;
        return false;
    }
    return true;
}

void Form_tf::on_leFph_returnPressed()
{
    on_pbSearch_clicked();
}

void Form_tf::on_pbExit_clicked()
{
    close();
}
bool Form_tf::fptp()
{
    //退发票

    if(mpPerson["pact_code"] == "2"){ //医保收费
        int ret;
        QString inp;
        char outp[1024];

        if(mpPerson["insurance_mode"] == "card" || mpPerson["insurance_mode"] == "id"){//刷卡或身份证
            //入参： 就诊流水号， 经办员姓名
            inp = pub::getYbStr("2430", mpPerson["clinic_code"]);
            if(inp.isEmpty()){ //返回空，未得到有效交易流水号
                QMessageBox::information(this,"错误","申请医保交易流水号失败！");
                return false;
            }
            inp.append(mpPerson["clinic_code"] + "|" );
            inp.append(mpPerson["invoice_no"] + "|" );
            inp.append(QDateTime::currentDateTime().toString("yyyyMMddHHmmss") + "|" );
            inp.append(pub::usr_name + "|" );
            inp.append("0|" );
            inp.append("OwnSoft|" );
            inp.append("^1^");   //

            if(mpPerson["insurance_mode"] == "id"){//身份证交易与刷卡相同，只是在最后增脱卡标志
                inp.append("1^");
            }
        }else if(mpPerson["insurance_mode"] == "code"){

            if(!getToken()){        //取交易令牌
                return false;
            }
            //入参： 就诊流水号，经办员姓名，用户姓名，证件号码，证件类型，令牌
            inp = pub::getYbStr("4102", mpPerson["clinic_code"]);
            if(inp.isEmpty()){ //返回空，未得到有效交易流水号
                QMessageBox::information(this,"错误","申请医保交易流水号失败！");
                return false;
            }
            inp.append(mpPerson["clinic_code"] + "|" );
            inp.append(mpPerson["invoice_no"] + "|" );
            inp.append(QDateTime::currentDateTime().toString("yyyyMMddHHmmss") + "|" );
            inp.append(pub::usr_name + "|" );
            inp.append("0|" );
            inp.append("OwnSoft|" );
            inp.append(mpPerson["name"] + "|" );
            inp.append(mpPerson["idenno"] + "|" );
            inp.append(mpPerson["card_type"] + "|" );
            inp.append(mpPerson["token"] + "|" );
            inp.append("^1^");   //

        }else{
            QMessageBox::information(this,"错误","医保支付方式错误，非卡，非扫码。");
            return false;
        }

        ret = pub::BUSINESS(inp.toLocal8Bit().data(),outp);
        if(ret != 0){
            QMessageBox::information(this,"错误","医保返回异常：" + QString::fromLocal8Bit(outp));
            return false;
        }
        //保存交易信息
        qrm->prepare("update com_business set jyfs = :jyfs, lpbz = :lpbz, zxjyls = :zxjyls "
                     "where atinc = :atinc");
        qrm->bindValue(":zxjyls", pub::getStr(QString::fromLocal8Bit(outp),"^",1));
        qrm->bindValue(":atinc", pub::ybywzqAtinc); //申请交易流水号时获得
        qrm->bindValue(":lpbz", mpPerson["token"]);  //读卡或扫码成功后获得
        qrm->bindValue(":jyfs", mpPerson["insurance_mode"]);  //交易方式，读卡或扫码
        qrm->exec();

        if(!saveSI()){    //保存退费交易
            QMessageBox::information(this,"错误","保存医保数据返回异常！");
            return false;
        }
    }

    qro->prepare("update fin_opb_invoiceinfo set CANCEL_FLAG='0' Where INVOICE_NO = :ivno ");
    qro->bindValue(":ivno", mpPerson["invoice_no"]);
    if(!qro->exec()){
        QMessageBox::information(this,"错误","更新 fin_opb_invoiceinfo 失败！"+qro->lastError().text());
        return false;
    }

    qro->prepare("Insert into fin_opb_invoiceinfo (INVOICE_NO,TRANS_TYPE,CARD_NO,"
                 "REG_DATE,NAME,PAYKIND_CODE,PACT_CODE,PACT_NAME,MCARD_NO,MEDICAL_TYPE,"
                 "TOT_COST,PUB_COST,OWN_COST,PAY_COST,BACK1,BACK2,BACK3,REAL_COST,"
                 "OPER_CODE,OPER_DATE,EXAMINE_FLAG,CANCEL_FLAG,CANCEL_INVOICE,"
                 "CANCEL_CODE,CANCEL_DATE,CHECK_FLAG,CHECK_OPCD,BALANCE_FLAG,BALANCE_NO,"
                 "BALANCE_OPCD,INVOICE_SEQ,EXT_FLAG,CLINIC_CODE,PRINT_INVOICENO,"
                 "DRUG_WINDOW,ACCOUNT_FLAG,BALANCE_COMBONO)"
                 " select INVOICE_NO,'2',CARD_NO,REG_DATE,NAME,PAYKIND_CODE,PACT_CODE,"
                 "PACT_NAME,MCARD_NO,MEDICAL_TYPE,0-TOT_COST,0-PUB_COST,0-OWN_COST,"
                 "0-PAY_COST,0-BACK1,BACK2,BACK3,0-REAL_COST,:OPER_CODE,sysdate,"
                 "EXAMINE_FLAG,'0',CANCEL_INVOICE,:OPER_CODE,sysdate,'0','','0',BALANCE_NO,"
                 "BALANCE_OPCD,INVOICE_SEQ,EXT_FLAG,CLINIC_CODE,PRINT_INVOICENO,"
                 "DRUG_WINDOW,ACCOUNT_FLAG,BALANCE_COMBONO "
                 " from fin_opb_invoiceinfo where invoice_no = :ivno"
                 );
    qro->bindValue(":OPER_CODE", pub::usr_code);
    qro->bindValue(":ivno", mpPerson["invoice_no"]);
    if(!qro->exec()){
        QMessageBox::information(this,"错误","插入 fin_opb_invoiceinfo 失败！"+qro->lastError().text());
        qDebug()<<qro->lastQuery();
        qDebug()<<":OPER_CODE" << pub::usr_code;
        qDebug()<<":ivno" << mpPerson["invoice_no"];
        return false;
    }

    qro->prepare("update fin_opb_invoicedetail set CANCEL_FLAG='0' Where INVOICE_NO = :ivno");
    qro->bindValue(":ivno", mpPerson["invoice_no"]);
    if(!qro->exec()){
        QMessageBox::information(this,"错误","更新 fin_opb_invoicedetail 失败！"+qro->lastError().text());
        return false;
    }

    qro->prepare("insert into fin_opb_invoicedetail (INVOICE_NO,TRANS_TYPE,INVO_SEQUENCE,"
                 "INVO_CODE,INVO_NAME,PUB_COST,OWN_COST,PAY_COST,DEPT_CODE,DEPT_NAME,"
                 "OPER_DATE,OPER_CODE,BALANCE_FLAG,BALANCE_NO,CANCEL_FLAG,INVOICE_SEQ)"
                 " select INVOICE_NO,'2',INVO_SEQUENCE,INVO_CODE,INVO_NAME,0-PUB_COST,"
                 "0-OWN_COST,0-PAY_COST,DEPT_CODE,DEPT_NAME,sysdate,:OPER_CODE,'0',"
                 "BALANCE_NO,CANCEL_FLAG,INVOICE_SEQ"
                 " from fin_opb_invoicedetail where INVOICE_NO = :ivno");
    qro->bindValue(":OPER_CODE", pub::usr_code);
    qro->bindValue(":ivno", mpPerson["invoice_no"]);
    if(!qro->exec()){
        QMessageBox::information(this,"错误","插入 fin_opb_invoiceinfo 失败！"+qro->lastError().text());
        qDebug()<<qro->lastQuery();
        qDebug()<<":OPER_CODE" << pub::usr_code;
        qDebug()<<":ivno" << mpPerson["invoice_no"];
        return false;
    }

    qro->prepare("update fin_opb_feedetail set CANCEL_FLAG='0' Where invoice_no = :ivno");
    qro->bindValue(":ivno", mpPerson["invoice_no"]);
    if(!qro->exec()){
        QMessageBox::information(this,"错误","更新 fin_opb_feedetail 失败！"+qro->lastError().text());
        return false;
    }

    qro->prepare("insert into fin_opb_feedetail ( RECIPE_NO,SEQUENCE_NO,TRANS_TYPE,CLINIC_CODE,"
                 "CARD_NO,REG_DATE,REG_DPCD,DOCT_CODE,DOCT_DEPT,ITEM_CODE,ITEM_NAME,DRUG_FLAG,"
                 "SPECS,SELF_MADE,DRUG_QUALITY,DOSE_MODEL_CODE,FEE_CODE,CLASS_CODE,UNIT_PRICE,"
                 "QTY,DAYS,FREQUENCY_CODE,USAGE_CODE,USE_NAME,INJECT_NUMBER,EMC_FLAG,LAB_TYPE,"
                 "CHECK_BODY,DOSE_ONCE,DOSE_UNIT,BASE_DOSE,PACK_QTY,PRICE_UNIT,PUB_COST,PAY_COST,"
                 "OWN_COST,EXEC_DPCD,EXEC_DPNM,CENTER_CODE,ITEM_GRADE,MAIN_DRUG,COMB_NO,OPER_CODE,"
                 "OPER_DATE,PAY_FLAG,CANCEL_FLAG,FEE_CPCD,FEE_DATE,INVOICE_NO,INVO_CODE,"
                 "INVO_SEQUENCE,CONFIRM_FLAG,CONFIRM_CODE,CONFIRM_DEPT,CONFIRM_DATE,"
                 "INVOICE_SEQ,NEW_ITEMRATE,OLD_ITEMRATE,EXT_FLAG,PACKAGE_CODE,PACKAGE_NAME,"
                 "EXT_FLAG1,EXT_FLAG2,EXT_FLAG3,NOBACK_NUM,CONFIRM_NUM,CONFIRM_INJECT,MO_ORDER,"
                 "RECIPE_SEQ,ECO_COST,over_cost,EXCESS_COST,DRUG_OWNCOST,COST_SOURCE,SUBJOB_FLAG,"
                 "ACCOUNT_FLAG,UPDATE_SEQUENCENO,doctindept,MEDICALGROUPCODE,ACCOUNT_NO)"
                 " select "
                 " RECIPE_NO,SEQUENCE_NO,'2',CLINIC_CODE,CARD_NO,REG_DATE,REG_DPCD,DOCT_CODE,"
                 "DOCT_DEPT,ITEM_CODE,ITEM_NAME,DRUG_FLAG,SPECS,SELF_MADE,DRUG_QUALITY,"
                 "DOSE_MODEL_CODE,FEE_CODE,CLASS_CODE,UNIT_PRICE,0-QTY,DAYS,FREQUENCY_CODE,"
                 "USAGE_CODE,USE_NAME,INJECT_NUMBER,EMC_FLAG,LAB_TYPE,CHECK_BODY,DOSE_ONCE,"
                 "DOSE_UNIT,BASE_DOSE,PACK_QTY,PRICE_UNIT,0-PUB_COST,0-PAY_COST,0-OWN_COST,"
                 "EXEC_DPCD,EXEC_DPNM,CENTER_CODE,ITEM_GRADE,MAIN_DRUG,COMB_NO,:FEE_CPCD,"
                 "sysdate,PAY_FLAG,CANCEL_FLAG,:FEE_CPCD,sysdate,INVOICE_NO,INVO_CODE,"
                 "INVO_SEQUENCE,CONFIRM_FLAG,CONFIRM_CODE,CONFIRM_DEPT,CONFIRM_DATE,"
                 "INVOICE_SEQ,NEW_ITEMRATE,OLD_ITEMRATE,EXT_FLAG,PACKAGE_CODE,PACKAGE_NAME,"
                 "EXT_FLAG1,EXT_FLAG2,EXT_FLAG3,NOBACK_NUM,CONFIRM_NUM,CONFIRM_INJECT,"
                 "MO_ORDER,RECIPE_SEQ,ECO_COST,over_cost,EXCESS_COST,DRUG_OWNCOST,COST_SOURCE,"
                 "SUBJOB_FLAG,ACCOUNT_FLAG,UPDATE_SEQUENCENO,doctindept,MEDICALGROUPCODE,"
                 "ACCOUNT_NO "
                 " from fin_opb_feedetail where invoice_no = :ivno");
    qro->bindValue(":FEE_CPCD", pub::usr_code);
    qro->bindValue(":ivno", mpPerson["invoice_no"]);
    if(!qro->exec()){
        QMessageBox::information(this,"错误","插入 fin_opb_invoiceinfo 失败！"+qro->lastError().text());
        qDebug()<<qro->lastQuery();
        qDebug()<<":OPER_CODE" << pub::usr_code;
        qDebug()<<":ivno" << mpPerson["invoice_no"];
        return false;
    }

    qro->prepare("update met_nui_cancelitem set charge_flag ='1',charge_code =:oper"
                 ",charge_date = sysdate where bill_no = :bn ");
    qro->bindValue(":oper", pub::usr_code);
    qro->bindValue(":bn", mpPerson["invoice_no"]);
    if(!qro->exec()){
        QMessageBox::information(this,"错误","插入 fin_opb_invoiceinfo 失败！"+qro->lastError().text());
        qDebug()<<qro->lastQuery();
        qDebug()<<":oper" << pub::usr_code;
        qDebug()<<":bn" << mpPerson["invoice_no"];
        return false;
    }

    return true;
}

bool Form_tf::getToken()
{
    //申请医保令牌
    QString inp;
    inp = pub::getYbStr("4100", mpPerson["clinic_code"]);
    if(inp.isEmpty()){ //返回空，未得到有效交易流水号
        return false;
    }
    inp = inp + "|01101|6757-" + pub::getStr(pub::localIP,".",4) +
            "|" + pub::localIP + "|" + pub::usr_code + "|" + pub::usr_name +
            "|" + pub::dp_code + "|" + pub::dp_name + "|^1^";   //
    char outp[1024];
    int ret=pub::BUSINESS(inp.toLocal8Bit().data(),outp);

    if(ret==0){
        QString retValue = pub::getStr(QString::fromLocal8Bit(outp),"^",3); //获取出参
        mpPerson["token"] = pub::getStr(retValue,"|",27);//令牌 VARHCAR2(40)用于业务处理验证

        //保存交易信息
        qrm->prepare("update com_business set jyfs = :jyfs, lpbz = :lpbz, zxjyls = :zxjyls "
                     "where atinc = :atinc");
        qrm->bindValue(":zxjyls", pub::getStr(QString::fromLocal8Bit(outp),"^",1));
        qrm->bindValue(":atinc", pub::ybywzqAtinc); //申请交易流水号时获得
        qrm->bindValue(":lpbz", mpPerson["token"]);  //读卡或扫码成功后获得
        qrm->bindValue(":jyfs", "code");  //交易方式，读卡或扫码
        qrm->exec();

    }else{
        QMessageBox::information(this,"错误","医保扫码失败！ " + QString::number(ret));
        return false;
    }
    return true;

}

void Form_tf::putBaseIn( QJsonObject &in, QString code)
{
    QString inp;
    inp = pub::getYbStrJ(code,"");   //
    if(inp.isEmpty()){
        pub::useInsurance = false;  //设置医保不可用
        QMessageBox::information(this,"note","申请交易流水号失败！");
        return; //未能成功申请交易流水号
    }

    msgid2208 = inp;

    in.insert("infno", code);
    in.insert( "msgid", inp);
    in.insert("mdtrtarea_admvs", pub::hos_insuplc);
    in.insert("insuplc_admdvs", mpPerson["insuplc_admdvs"] );

    in.insert("insuplc_admdvs","210100");
    in.insert("recer_sys_code", "OwnSoft");
    in.insert("dev_no","");
    in.insert("dev_safe_info","");
    in.insert("cainfo", pub::hos_secretcode);
    in.insert("signtype","");
    in.insert("infver", "V1.0");
    in.insert("opter_type", "1");
    in.insert("opter", pub::usr_code);
    in.insert("opter_name", pub::usr_name);
    in.insert("inf_time", QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"));
    in.insert("fixmedins_code", pub::hos_ybbh);
    in.insert("fixmedins_name", pub::hos_name);
    in.insert("sign_no", pub::sign_no);

}


void Form_tf::postRequestFinished(QNetworkReply *rpl)
{
    httpFinished = true;
qDebug()<<"http is finished in subroutin";
    QVariant statusCode = rpl->attribute(QNetworkRequest::HttpStatusCodeAttribute);

    if(!statusCode.isValid()){
        QMessageBox::warning(NULL,"注意","http 请求状态错误: " + statusCode.toString());
        httpSuccess = false;
qDebug()<<"http request error";
        return;
    }

    QNetworkReply::NetworkError err = rpl->error();

    if(err != QNetworkReply::NoError){
        QMessageBox::warning(NULL,"注意",rpl->errorString());
        httpSuccess = false;
qDebug()<<"http error";
        return;
    }else{
        QByteArray bt = rpl->readAll();
        QString t = QString::fromLocal8Bit(bt);

        QJsonParseError json_error;
        QJsonDocument jsdc = QJsonDocument::fromJson(t.toUtf8(), &json_error);
        if(json_error.error != 0 ){
            QMessageBox::warning(NULL,"注意","返回信息解析错误 " + json_error.errorString());
            httpSuccess = false;
            return;
        }
        qDebug()<< "2208 outDoc "<<jsdc;
        QJsonObject jsob = jsdc.object();

        if(jsob.value("infcode").toInt() != 0){
            QString t = jsob.value("err_msg").toString();
            QMessageBox::warning(NULL,"注意","2208 交易失败：" + t );
            httpSuccess = false;
            return;
        }
        ret2208setlinfo = jsob.value("output").toObject().value("setlinfo").toObject();
        ret2208setldetail = jsob.value("output").toObject().value("setldetail").toObject();

        httpSuccess = true;
        qDebug()<<"httpSuccess is "<<httpSuccess;
    }
}
